package com.wwt.blog.handler;

import com.alibaba.fastjson.JSON;
import com.wwt.blog.imp.SysUserServiceImp;
import com.wwt.blog.pojo.SysUser;
import com.wwt.blog.service.SysUserService;
import com.wwt.blog.utils.UserThreadLocal;
import com.wwt.blog.vo.ErrorCode;
import com.wwt.blog.vo.Result;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Log4j2
//登录拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    SysUserServiceImp sysUserServiceImp;
    //在执行controller之前拦截
    /**
     * 1. 需要判断 请求的接口路径 是否为 HandlerMethod (controller方法)
     * 2. 判断 token是否为空，如果为空 未登录
     * 3. 如果token 不为空，登录验证 loginService checkToken
     * 4. 如果认证成功 放行即可
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断接口路径
        if(!(handler instanceof HandlerMethod))
            return true;
        System.out.println("###########################");
        String token=request.getHeader("Authorization");
       log.info("URL为：{}",request.getRequestURL());
       log.info("Token为：{}",request.getHeader("Authorization"));
       log.info("方法为：{}",request.getMethod());

        if (StringUtils.isEmpty(token))
        {
            Result result=Result.result_fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
            //设置返回的格式
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //检查token
         SysUser user=sysUserServiceImp.checkToken(token);
        if(user==null)
        {
           Result result=Result.result_fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
           response.setContentType("application/json;charset=utf-8");
           response.getWriter().print(JSON.toJSONString(result));

           return false;
        }
        //认证通过 放行 存入ThreadLocal
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThreadLocal中用完的信息
        UserThreadLocal.remove();
    }
}
